package com.situ.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.entity.Category;
import com.situ.service.CategoryService;
import com.situ.service.impl.CategoryServiceImpl;
import com.situ.vo.TableVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author yangkx
 * @create 2023-09-09-0:37
 */
@WebServlet("/category")
public class CategoryController extends BaseController{

    CategoryService service = new CategoryServiceImpl();

    //打开页面
    public void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/ControllerPage/category.jsp").forward(req,resp);
    }

    //查询表格数据
    public TableVO select() {
        return service.list();
    }

    //发请求去查分类数据
    public List<Category> all(){
        return service.all();
    }

    //保存分类数据
    public void save(Category c){
        service.save(c);
    }

    //删除分类数据
    public void delete(Integer id){
        service.delete(id);
    }

    //根据id查分类数据 带到前台
    public void selectById(Integer id,HttpServletResponse response) throws IOException {
        Category c = service.selectById(id);

        //避免乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        //把Product对象转换成json格式字符串
        String s = new ObjectMapper().writeValueAsString(c);
        //往前台写
        response.getWriter().write(s);
    }

}
